package com.zzyl.nursing.job;

import com.zzyl.nursing.domain.HourTime;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;


@Component
public class TimeCalculator {

    public List<HourTime> calculateHourlyTimes(long startTime, long endTime) {
        List<HourTime> hourlyTimes = new ArrayList<>();
        
        // 定义东八区时区
        ZoneId zoneId = ZoneId.of("Asia/Shanghai"); // 或者使用 ZoneId.of("Etc/GMT-8")
        
        // 将时间戳转换为 ZonedDateTime 并指定时区
        ZonedDateTime startZonedDateTime = ZonedDateTime.ofInstant(
            Instant.ofEpochMilli(startTime), zoneId);
        ZonedDateTime endZonedDateTime = ZonedDateTime.ofInstant(
            Instant.ofEpochMilli(endTime), zoneId);

        // 转换为 LocalDateTime
        LocalDateTime startDateTime = startZonedDateTime.toLocalDateTime();
        LocalDateTime endDateTime = endZonedDateTime.toLocalDateTime();

        // 确保开始时间小于等于结束时间
        if (startDateTime.isAfter(endDateTime)) {
            throw new IllegalArgumentException("Start time must be before end time.");
        }
        
        while (startDateTime.isBefore(endDateTime)) {
            LocalDateTime hourStart = startDateTime;
            LocalDateTime hourEnd = startDateTime.plusHours(1).minusSeconds(1); // 确保不会超过 endTime
            
            hourlyTimes.add(new HourTime(hourStart, hourEnd));
            
            startDateTime = startDateTime.plusHours(1);
        }
        
        return hourlyTimes;
    }

    // 计算每日的开始时间和结束时间
    public List<HourTime> calculateDailyTimes(long startTime, long endTime) {
        List<HourTime> dailyTimes = new ArrayList<>();

        // 定义东八区时区
        ZoneId zoneId = ZoneId.of("Asia/Shanghai"); // 或者使用 ZoneId.of("Etc/GMT-8")

        // 将时间戳转换为 ZonedDateTime 并指定时区
        ZonedDateTime startZonedDateTime = ZonedDateTime.ofInstant(
                Instant.ofEpochMilli(startTime), zoneId);
        ZonedDateTime endZonedDateTime = ZonedDateTime.ofInstant(
                Instant.ofEpochMilli(endTime), zoneId);

        // 转换为 LocalDateTime
        LocalDateTime startDateTime = startZonedDateTime.toLocalDateTime();
        LocalDateTime endDateTime = endZonedDateTime.toLocalDateTime();

        // 确保开始时间小于等于结束时间
        if (startDateTime.isAfter(endDateTime)) {
            throw new IllegalArgumentException("Start time must be before end time.");
        }

        // 计算每天的开始时间和结束时间
        while (startDateTime.isBefore(endDateTime)) {
            LocalDateTime dayStart = startDateTime.withHour(0).withMinute(0).withSecond(0).withNano(0);
            LocalDateTime dayEnd = dayStart.plusDays(1).minusSeconds(1);

            dailyTimes.add(new HourTime(dayStart, dayEnd));

            startDateTime = startDateTime.plusDays(1);
        }

        return dailyTimes;
    }

}
